﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SlamCms.Common;
using SlamCms.Web;

namespace System.Web.Mvc
{
	public static class TagBrowserUrlExtensions
	{
		public static string TagBrowser(this UrlHelper urlHelper, string tagBrowserId, string[] tags = null, object routeValues = null)
		{
			return urlHelper.TagBrowser(tagBrowserId, tags, new RouteValueDictionary(routeValues));
		}

		public static string TagBrowser(this UrlHelper urlHelper, string tagBrowserId, string[] tags, RouteValueDictionary routeValues)
		{
			if (tagBrowserId.IsNullOrWhiteSpace())
				throw new ArgumentException("The tagBrowserId cannot be null or an empty string", "tagBrowserId");

			var tagBrowser = TagBrowsers.Browsers.FirstOrDefault(t => t.Id == tagBrowserId);

			if (tagBrowser == null)
				throw new Exception("The tag browser with id {0} does not exists. Please check the TagBrowsers.Browsers collection.".F(tagBrowserId));

			//var controller = tagBrowser.RouteValues["controller"].ToString();
			//var action = tagBrowser.RouteValues["action"].ToString();

			if (tags == null)
				tags = new string[] { };

			var tagsString = string.Join("/", tags);

			var routeValuesDictionary = new RouteValueDictionary(tagBrowser.RouteValues);
			routeValuesDictionary.Add("tags", tagsString);
				
			foreach (var routeValue in routeValues)
				routeValuesDictionary[routeValue.Key] = routeValue.Value;

			return urlHelper.RouteUrl(routeValuesDictionary);
		}

		public static TagBrowserUrlHelper TagBrowser(this UrlHelper urlHelper, string tagBrowserId)
		{
			return new TagBrowserUrlHelper(urlHelper, tagBrowserId);
		}

		public static TagBrowserUrlHelper TagBrowser(this UrlHelper urlHelper, TagBrowserParameters parameters)
		{
			return new TagBrowserUrlHelper(urlHelper, parameters.TagBrowser.Id).AddTags(parameters.FilteredTags);
		}
	}
}